package com.laowang.framework.security.filter;

import com.laowang.common.exception.BaseException;
import com.laowang.common.utils.SecurityUtils;
import com.laowang.common.utils.StringUtils;
import com.laowang.framework.security.LoginUser;
import com.laowang.framework.security.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器 验证token有效性
 *
 * @author laowang
 * description   每一次请求都会走这里 要是路径放行的 就直接走 没放行的就验证一下token的过期时间 要是过期了就刷新一次token
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
        // 从header 中取到 token 是 Authorization Bearer token值  解析token的值得到 claims 在根据String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);得到uuid,得到 String userKey = getTokenKey(uuid);在 LoginUser user = redisCache.getCacheObject(userKey);
        LoginUser loginUser = tokenService.getLoginUser(request);

        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication())) {
            // 校验这个用户的 loginUser 中存的 token 的时间 不足20分钟就自动续命 成30分钟
            tokenService.verifyToken(loginUser);
            //                                                                                                // 登录的主体信息        // 权限
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //交给spring security管理,在之后的过滤器中不会再被拦截进行二次授权了
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        }
        chain.doFilter(request, response);

    }
}

